package cc.fs.kotlin.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.widget.TextView
import cc.fs.kotlin.R
import cc.fs.kotlin.ui.activity.helper.BaseActivity
import cc.fs.kotlin.utils.bindView
import com.edmodo.cropper.CropImageView


import java.io.ByteArrayOutputStream
import java.io.File
import kotlin.collections.dropLastWhile
import kotlin.collections.toTypedArray
import kotlin.text.*

/**
 * 选择图片并且剪切图片
 */
class CropActivity : BaseActivity() {

    val cropperView: CropImageView by bindView(R.id.cropImageView)
    val okBtn: TextView by bindView(R.id.okBtn)
    val toolbar: Toolbar by bindView(R.id.toolbar)

    private var imageFilePath: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_crop)

        setUpView()
        loadImage()

        //申请权限
        //        UIHelper.requestPermission(this@CropActivity, object : OnRequestPermissionsListener {
        //            override fun onRequestPermissionsResult(permissions: Map<String, Boolean>) {
        //                if (permissions.containsValue(false)) {
        //                    showToast("您需要授予权限才能使用APP")
        //                    finish()
        //                    return
        //                }
        //            }
        //        }, Manifest.permission.READ_EXTERNAL_STORAGE)
    }

    public fun setUpView() {
        toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha)
        toolbar.title = getString(R.string.title_activity_crop)
        setSupportActionBar(toolbar)

        cropperView.setAspectRatio(1, 1)
        cropperView.setGuidelines(2)
        cropperView.setFixedAspectRatio(true)

        okBtn.setOnClickListener {
            var rlt = cropperView.croppedImage
            val rect = cropperView.actualCropRect
            val w = rect.width().toInt()
            if (w > MAX_PIXEL) {
                rlt = zoomBitmap(rlt, MAX_PIXEL, MAX_PIXEL)
            }

            val intent = Intent()
            intent.putExtra("bitmap", Bitmap2Bytes(rlt))
            setResult(Activity.RESULT_OK, intent)

            finish()
        }
    }

    private fun loadImage() {
        try {

            imageFilePath = intent.getStringExtra("path")
            if(TextUtils.isEmpty(imageFilePath)){
                showToast("图片非法!")
                finish()
            }

            val dm = this.resources.displayMetrics
            val screen_width = dm.widthPixels

            val bitmapFactoryOptions = BitmapFactory.Options()
            bitmapFactoryOptions.inJustDecodeBounds = true
            BitmapFactory.decodeFile(imageFilePath, bitmapFactoryOptions)

            val widthRatio = Math.floor((bitmapFactoryOptions.outWidth / screen_width.toFloat()).toDouble()).toInt()

            bitmapFactoryOptions.inSampleSize = widthRatio
            bitmapFactoryOptions.inJustDecodeBounds = false
            val bitmap = BitmapFactory.decodeFile(imageFilePath, bitmapFactoryOptions)

            //imageView.setImageBitmap(bitmap);
            cropperView.setImageBitmap(bitmap)

        } catch (e: Exception) {
            e.printStackTrace()
            finish()
        }
    }

    private fun Bitmap2Bytes(bm: Bitmap): ByteArray {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        return baos.toByteArray()
    }

    private fun zoomBitmap(bitmap: Bitmap?, w: Int, h: Int): Bitmap? {
        var newBitmap: Bitmap? = null
        if (bitmap != null) {
            val width = bitmap.width
            val height = bitmap.height
            val matrix = Matrix()
            val scaleWidht = (w.toFloat() / width)
            val scaleHeight = (h.toFloat() / height)
            matrix.postScale(scaleWidht, scaleHeight)
            newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true)
        }
        return newBitmap
    }

    override fun handler(msg: Message) {

    }

    companion object {
        val FALG_CROP = 102
        private val MAX_PIXEL = 256

        fun start(context: Activity,path:String ) {
            val intent:Intent = Intent(context, CropActivity::class.java)
            intent.putExtra("path",path)
            context.startActivityForResult(intent,FALG_CROP)
        }
    }
}
